package com.dkd.manage.task.allocator.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeePerformance {
    private Long empId;
    private Integer completedTasks = 0;
    private Integer totalTasks = 0;
    private Double avgCompletionTime = 4.0;
    private Double successRate = 0.85;
    private Integer currentWorkload = 0;
    private Integer todayTasks = 0;
    private Double avgQualityScore = 5.0;
    private Double completionRate = 0.8;
    private Set<String> skilledMachines = new HashSet<>();
    private Double performanceScore = 6.0;
    private Date lastUpdateTime = new Date();

    // 新增字段
    private Integer skillLevel = 1;
    private Double responseRate = 0.9;
    private Integer specializedMachinesCount = 0;
    private Double efficiencyIndex = 1.0;
    private Double reliabilityScore = 0.8;

    // 业务方法保持不变...
    public Integer getSkillLevel() {
        return skillLevel != null ? skillLevel : 1;
    }

    public void setSkillLevel(Integer skillLevel) {
        if (skillLevel != null && skillLevel >= 1 && skillLevel <= 5) {
            this.skillLevel = skillLevel;
        } else {
            this.skillLevel = 1;
        }
    }

    /**
     * 获取综合能力评分
     */
    public Double getComprehensiveAbility() {
        double ability = 0.0;
        ability += (getSkillLevel() / 5.0) * 0.3;           // 技能等级占30%
        ability += (getPerformanceScore() / 10.0) * 0.4;    // 绩效得分占40%
        ability += getSuccessRate() * 0.2;                  // 成功率占20%
        ability += getEfficiencyIndex() * 0.1;              // 效率指数占10%
        return Math.min(ability, 1.0);
    }

    /**
     * 判断是否具备指定技能等级
     */
    public boolean hasSkillLevel(Integer requiredLevel) {
        return getSkillLevel() >= (requiredLevel != null ? requiredLevel : 1);
    }

    /**
     * 获取效率指数
     */
    public Double getEfficiencyIndex() {
        if (efficiencyIndex == null) {
            // 基于平均完成时间计算效率指数
            if (avgCompletionTime <= 2.0) return 1.2;
            if (avgCompletionTime <= 3.0) return 1.1;
            if (avgCompletionTime <= 4.0) return 1.0;
            if (avgCompletionTime <= 5.0) return 0.9;
            if (avgCompletionTime <= 6.0) return 0.8;
            return 0.7;
        }
        return efficiencyIndex;
    }

    /**
     * 获取可靠性评分
     */
    public Double getReliabilityScore() {
        if (reliabilityScore == null) {
            // 基于成功率和完成率计算可靠性
            return (successRate * 0.6) + (completionRate * 0.4);
        }
        return reliabilityScore;
    }

    /**
     * 获取专长设备数量
     */
    public Integer getSpecializedMachinesCount() {
        if (specializedMachinesCount == null) {
            return skilledMachines != null ? skilledMachines.size() : 0;
        }
        return specializedMachinesCount;
    }

    /**
     * 判断是否擅长指定设备类型
     */
    public boolean isSkilledInMachine(String vmTypeId) {
        return skilledMachines != null && skilledMachines.contains(vmTypeId);
    }

    /**
     * 获取技能匹配度
     */
    public Double getSkillMatchLevel(String vmTypeId) {
        if (isSkilledInMachine(vmTypeId)) {
            return 1.0; // 完全匹配
        } else if (getSpecializedMachinesCount() > 0) {
            return 0.7; // 有相关经验
        } else {
            return 0.3; // 无经验
        }
    }

    /**
     * 获取工作负载等级
     */
    public Double getWorkloadLevel() {
        if (currentWorkload == 0) return 0.1;
        if (currentWorkload <= 2) return 0.3;
        if (currentWorkload <= 4) return 0.5;
        if (currentWorkload <= 6) return 0.7;
        return 0.9;
    }

    /**
     * 判断是否超负荷
     */
    public boolean isOverloaded() {
        return currentWorkload >= 8 || todayTasks >= 10;
    }

    /**
     * 获取响应率
     */
    public Double getResponseRate() {
        if (responseRate == null) {
            // 基于历史数据计算响应率
            if (completedTasks == 0) return 0.9;
            double timelyRate = Math.min(1.0, (double) completedTasks / totalTasks);
            return (timelyRate * 0.7) + (successRate * 0.3);
        }
        return responseRate;
    }

    /**
     * 获取绩效等级
     */
    public String getPerformanceGrade() {
        double score = getPerformanceScore();
        if (score >= 9.0) return "A+";
        if (score >= 8.0) return "A";
        if (score >= 7.0) return "B+";
        if (score >= 6.0) return "B";
        if (score >= 5.0) return "C";
        return "D";
    }

    /**
     * 更新绩效数据
     */
    public void updatePerformance(Integer newCompletedTasks, Integer newTotalTasks,
                                  Double newAvgCompletionTime, Double newSuccessRate) {
        if (newCompletedTasks != null) this.completedTasks = newCompletedTasks;
        if (newTotalTasks != null) this.totalTasks = newTotalTasks;
        if (newAvgCompletionTime != null) this.avgCompletionTime = newAvgCompletionTime;
        if (newSuccessRate != null) this.successRate = newSuccessRate;

        // 重新计算绩效得分
        this.performanceScore = calculateUpdatedPerformanceScore();
        this.lastUpdateTime = new Date();
    }

    /**
     * 计算更新的绩效得分
     */
    private Double calculateUpdatedPerformanceScore() {
        double score = 0.0;

        // 1. 工作效率 (30%)
        score += calculateEfficiencyComponent() * 0.3;

        // 2. 工作质量 (25%)
        score += calculateQualityComponent() * 0.25;

        // 3. 可靠性 (20%)
        score += calculateReliabilityComponent() * 0.2;

        // 4. 经验水平 (15%)
        score += calculateExperienceComponent() * 0.15;

        // 5. 响应能力 (10%)
        score += calculateResponsivenessComponent() * 0.1;

        return Math.min(score, 10.0);
    }

    private double calculateEfficiencyComponent() {
        if (avgCompletionTime <= 2.0) return 10.0;
        if (avgCompletionTime <= 3.0) return 9.0;
        if (avgCompletionTime <= 4.0) return 7.0;
        if (avgCompletionTime <= 5.0) return 5.0;
        return 3.0;
    }

    private double calculateQualityComponent() {
        if (avgQualityScore >= 9.0) return 10.0;
        if (avgQualityScore >= 8.0) return 9.0;
        if (avgQualityScore >= 7.0) return 7.0;
        if (avgQualityScore >= 6.0) return 5.0;
        return 3.0;
    }

    private double calculateReliabilityComponent() {
        return getReliabilityScore() * 10;
    }

    private double calculateExperienceComponent() {
        if (completedTasks >= 50) return 10.0;
        if (completedTasks >= 30) return 8.0;
        if (completedTasks >= 15) return 6.0;
        if (completedTasks >= 5) return 4.0;
        return 2.0;
    }

    private double calculateResponsivenessComponent() {
        return getResponseRate() * 10;
    }

    /**
     * 验证绩效数据的有效性
     */
    public boolean isValid() {
        return empId != null &&
                completedTasks >= 0 &&
                totalTasks >= completedTasks &&
                avgCompletionTime > 0 &&
                successRate >= 0 && successRate <= 1;
    }

    /**
     * 获取绩效摘要
     */
    public String getPerformanceSummary() {
        return String.format("员工%d: 等级%s, 绩效%s, 成功率%.1f%%, 负载%d/%d",
                empId, getSkillLevel(), getPerformanceGrade(),
                successRate * 100, currentWorkload, todayTasks);
    }

    @Override
    public String toString() {
        return "EmployeePerformance{" +
                "empId=" + empId +
                ", skillLevel=" + skillLevel +
                ", performanceScore=" + performanceScore +
                ", successRate=" + successRate +
                ", currentWorkload=" + currentWorkload +
                ", completedTasks=" + completedTasks +
                '}';
    }
}